import {
  UserHttp
} from '../../../api/user'
import util from '../../../utils/utils'

const userModel = new UserHttp()
let timer = null

Page({
  /**
   * 页面的初始数据
   */
  data: {
    weekCost: 0, // 周累计消费
    mouthCost: 0, // 月累计消费
    exchangeGoodsList: [], // 兑换商品列表
    isShowExchangeRule: false, // 是否显示兑换规则
    noticeSwiperWidth: 0, // 通知轮播区域宽度
    noticeContentWidth: 0, // 通知内容宽度
    noticeDuration: 0, // 通知动画持续时间
    animationData: null,
    // timer: null
  },

  initPage() {
    this.setNavigationBar()
  },

  setNavigationBar() {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#fb6a22'
    })
  },

  // 显示兑换规则
  onShowExchangeRule() {
    this.setData({
      isShowExchangeRule: true
    })
  },

  // 关闭兑换规则
  onCloseExchangeRule() {
    this.setData({
      isShowExchangeRule: false
    })
  },

  initGetRects () {
    Promise.all([
      this.getRect('.marquee-swiper'),
      this.getRect('.marquee-content')
    ]).then((rects) => {
      console.log('initGetRects rects', rects)
      const [swiperRect, contentRect] = rects
      if (contentRect == null ||
        swiperRect == null ||
        !contentRect.width ||
        !swiperRect.width) {
        return;
      }
      if (swiperRect.width < contentRect.width) {
        this.setData({
          noticeSwiperWidth: swiperRect.width,
          noticeContentWidth: contentRect.width,
          noticeDuration: (contentRect.width / 50) * 1000
        })
        this.scroll()
      }
    })
  },

  scroll () {
    const { noticeSwiperWidth, noticeContentWidth, noticeDuration } = this.data
    timer && clearTimeout(timer);
    timer = null;
    this.setData({
      animationData: wx.createAnimation({
          duration: 0,
          timingFunction: 'linear'
        }).translateX(noticeSwiperWidth)
        .step()
        .export()
    })
    setTimeout(() => {
      this.setData({
        animationData: wx.createAnimation({
            duration: noticeDuration, // 动画持续时间
            timingFunction: 'linear', // 动画的效果
            delay: 1 // 动画延迟时间
          }).translateX(-noticeContentWidth)
          .step()
          .export()
      })
    }, 20)
    timer = setTimeout(() => {
      this.scroll();
    }, noticeDuration);
  },

  // 生命周期函数--监听页面显示
  onShow () {
    this.httpIntegralExchange()
  },

  // 页面相关事件处理函数--监听用户下拉动作
  async onPullDownRefresh () {
    await this.httpIntegralExchange()
    wx.stopPullDownRefresh()
  },

  // 页面上拉触底事件的处理函数
  onReachBottom () {
  },

  // 获取积分兑换基本信息
  httpIntegralExchange() {
    return userModel.integralExchange().then(res => {
      this.setData({
        weekCost: res.week_cost,
        mouthCost: res.mouth_cost,
        noticeList: res.band_list,
        exchangeGoodsList: res.list,
      })
      if (res.band_list && res.band_list.length) {
        this.initGetRects()
      }
    })
  },

  // 领券
  onReceive(event) {
    let goods  = event.detail
    this.httpCostGiftRecv(goods)
  },

  //领取礼品
  httpCostGiftRecv(goods) {
    let serviceId = wx.getStorageSync('servicePointInfo_2').serviceCenterId
    userModel.costGiftRecv({
      gift_id: goods.gift_id
    }).then((res) => {
      // this.httpIntegralExchange()
      wx.navigateTo({
        url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify([{ "sku_id": goods.sku_id, "spu_id": goods.spu_id, "amount": 1 }])}&storeId=${goods.store_id}&serviceId=${serviceId}&isGift=1&couponId=${res.coupon_sn}`
      })
    }).catch((err) => {
      util.msg(err.detail)
      console.log(err)
    })
  },

  // 获取节点信息的对象
  getRect(selector, all) {
    return new Promise(resolve => {
      wx.createSelectorQuery()
        .in(this)[all ? 'selectAll' : 'select'](selector)
        .boundingClientRect(rect => {
          if (all && Array.isArray(rect) && rect.length) {
            resolve(rect);
          }
          if (!all && rect) {
            resolve(rect);
          }
        })
        .exec();
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})
